package com.ruoyi.project.mobile;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.R;
import com.ruoyi.common.utils.RFactory;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uniquekey.IdGererateFactory;
import com.ruoyi.common.utils.wxmessage.SendWxMessage;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.jiaqin.apply.domain.CompanyApply;
import com.ruoyi.project.jiaqin.apply.service.ICompanyApplyService;
import com.ruoyi.project.jiaqin.company.domain.Company;
import com.ruoyi.project.jiaqin.company.service.ICompanyService;
import com.ruoyi.project.jiaqin.quotation.domain.Quotation;
import com.ruoyi.project.jiaqin.quotation.service.IQuotationService;
import com.ruoyi.project.jiaqin.vipconfig.domain.VipConfig;
import com.ruoyi.project.jiaqin.vipconfig.service.IVipConfigService;
import com.ruoyi.project.system.address.domain.MemberAddress;
import com.ruoyi.project.system.address.service.IMemberAddressService;
import com.ruoyi.project.system.coinrecord.domain.HaoqiCoinRecord;
import com.ruoyi.project.system.coinrecord.service.IHaoqiCoinRecordService;
import com.ruoyi.project.system.goods.cart.service.IShoppingCartService;
import com.ruoyi.project.system.goods.fee.service.IGoodsPostFeeService;
import com.ruoyi.project.system.goods.img.service.IGoodsImgService;
import com.ruoyi.project.system.goods.product.service.IGoodsProductService;
import com.ruoyi.project.system.goodsteam.domain.GoodsTeam;
import com.ruoyi.project.system.goodsteam.service.IGoodsTeamService;
import com.ruoyi.project.system.member.domain.Member;
import com.ruoyi.project.system.member.enums.MemberIsVip;
import com.ruoyi.project.system.member.service.IMemberService;
import com.ruoyi.project.system.oederteamgoods.domain.OrderTeamGoods;
import com.ruoyi.project.system.oederteamgoods.domain.OrderTeamGoodsDto;
import com.ruoyi.project.system.oederteamgoods.service.IOrderTeamGoodsService;
import com.ruoyi.project.system.order.comment.service.IOrderCommentService;
import com.ruoyi.project.system.order.commentimg.service.ICommentImgService;
import com.ruoyi.project.system.order.order.enums.OrderPayType;
import com.ruoyi.project.system.order.order.enums.OrderStatus;
import com.ruoyi.project.system.order.refuse.service.IOrderRefuseService;
import com.ruoyi.project.system.orderteamorder.domain.OrderTeamOrder;
import com.ruoyi.project.system.orderteamorder.domain.OrderTeamOrderDto;
import com.ruoyi.project.system.orderteamorder.service.IOrderTeamOrderService;
import com.ruoyi.project.system.orderteamuser.domain.OrderTeamUser;
import com.ruoyi.project.system.orderteamuser.service.IOrderTeamUserService;
import com.ruoyi.project.system.paylog.domain.PayLog;
import com.ruoyi.project.system.paylog.service.IPayLogService;
import com.ruoyi.project.system.shopconfig.domain.ShopConfig;
import com.ruoyi.project.system.shopconfig.service.IShopConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 注释
 *
 * @autor LCL
 * @date - 2021/3/10
 */
@RestController
@RequestMapping("/api/test")
public class ApiTestController extends BaseController {

    @Autowired
    private IGoodsTeamService goodsTeamService;
    @Autowired
    private IGoodsImgService goodsImgService;
    @Autowired
    private IGoodsProductService goodsProductService;
    @Autowired
    private IMemberAddressService memberAddressService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IGoodsPostFeeService goodsPostFeeService;
    @Autowired
    private IdGererateFactory idGererateFactory;
    @Autowired
    private IOrderTeamOrderService orderTeamOrderService;
    @Autowired
    private IOrderTeamGoodsService orderTeamGoodsService;
    @Autowired
    private IShoppingCartService shoppingCartService;
    @Autowired
    private IOrderCommentService orderCommentService;
    @Autowired
    private ICommentImgService commentImgService;
    @Autowired
    private IOrderRefuseService orderRefuseService;
    @Autowired
    private IPayLogService payLogService;
    @Autowired
    private IOrderTeamUserService orderTeamUserService;
    @Autowired
    private ICompanyService companyService;

    /**
     * 测试
     */
    @PostMapping("/cs")
    public R cs(@RequestBody OrderTeamOrderDto orderTeamOrderDto) {
        //生成 上级订单ID
        String superOrderId = "";
        if(orderTeamOrderDto.getGoodsList().size()>1){
            superOrderId = this.idGererateFactory.nextId().toString();
        }

        String orderId = "";

        for(OrderTeamGoods orderTeamGoods:orderTeamOrderDto.getGoodsList()){
            OrderTeamOrder orderTeam = new OrderTeamOrder();
            orderTeam.setUserId(orderTeamOrderDto.getUserId());
            orderTeam.setPostFee(orderTeamGoods.getPostFee());
//            orderTeam.setPricePay(orderTeamGoods.getPriceN().multiply(new BigDecimal(orderTeamGoods.getTotal())).add(orderTeam.getPostFee()));
            orderTeam.setPriceRealPay(orderTeam.getPricePay());
            orderTeam.setBuyerMsg(orderTeamOrderDto.getBuyerMsg());
            orderTeam.setConsigneeName(orderTeamOrderDto.getConsigneeName());
            orderTeam.setConsigneeTel(orderTeamOrderDto.getConsigneeTel());
            orderTeam.setAddress(orderTeamOrderDto.getAddress());
            orderTeam.setArea(orderTeamOrderDto.getArea());
            if(orderTeamOrderDto.getGoodsList().size()>1){
                orderTeam.setSuperOrderId(superOrderId);
            }

            orderTeam.setOrderNo(this.idGererateFactory.nextId().toString());
            orderTeam.setStatus(OrderStatus.TO_BE_PAID.getValue());
            orderTeam.setCreated(DateUtils.getNowDate());
            orderTeam.setDelFlag(0);
            orderTeam.setIsRefund(0);
            orderTeam.setId(idGererateFactory.nextStringId());
            this.orderTeamOrderService.insertOrderTeamOrder(orderTeam);
            //添加订单下的产品信息
            orderTeamGoods.setOrderId(orderTeam.getId());
            orderTeamGoods.setHasComent(0);
            orderTeamGoods.setId(idGererateFactory.nextStringId());
            this.orderTeamGoodsService.insertOrderTeamGoods(orderTeamGoods);

            if(orderTeamOrderDto.getGoodsList().size()>1){
                orderTeam.setSuperOrderId(superOrderId);
                orderId = superOrderId;
            }else{
                orderId = orderTeam.getId();
            }

            // 添加拼团订单人员表
            OrderTeamUser orderTeamUser = new OrderTeamUser();
            orderTeamUser.setId(idGererateFactory.nextStringId());
            orderTeamUser.setOrderId(orderTeam.getId());
            orderTeamUser.setCreateAt(DateUtils.getNowDate());
            orderTeamUser.setOrderTeamGoodsId(orderTeamGoods.getId());

            // 判断是否是拼团发起人
            if (!StringUtils.isBlank(orderTeamOrderDto.getMemberId())) {
                String oId = "";
                OrderTeamOrder oto = new OrderTeamOrder();
                oto.setStatus(9);
                oto.setUserId(orderTeamOrderDto.getMemberId());
                // 拼团订单列表
                List<OrderTeamOrder> teamOrderList = this.orderTeamOrderService.selectOrderTeamOrderList(oto);
                if (teamOrderList.size()>0) {
                    for (OrderTeamOrder orderTeamO:teamOrderList) {
                        // 某一条拼团订单
                        OrderTeamOrderDto byOrderNo = this.orderTeamOrderService.findByOrderNo(orderTeamO.getOrderNo());
                        for(OrderTeamGoods orderTGoods:orderTeamOrderDto.getGoodsList()){
                            OrderTeamGoodsDto teamGoodsDto = orderTeamGoodsService.findByOrderId(byOrderNo.getId());
                            if (teamGoodsDto.getGoodsId().equals(orderTGoods.getGoodsId())) {
                                oId = teamGoodsDto.getOrderId();
                            }
                        }
                    }
                    // 通过orderId查拼团订单人
                    OrderTeamUser orderTeamUserByOrderId = this.orderTeamUserService.findByOrderId(oId);
                    // 通过teamID查拼团订单条数
                    List<OrderTeamUser> listByTeamId = orderTeamUserService.findListByTeamId(orderTeamUserByOrderId.getTeamId());
                    // 判断是否超过拼团人数
                    GoodsTeam goodsTeamById = this.goodsTeamService.selectGoodsTeamById(orderTeamGoods.getGoodsId());
                    if (goodsTeamById.getNumber()>listByTeamId.size()) {
                        orderTeamUser.setIsMain(0);
                        orderTeamUser.setTeamId(orderTeamUserByOrderId.getTeamId());
                        this.orderTeamUserService.insertOrderTeamUser(orderTeamUser);
                    } else {
                        orderTeamUser.setIsMain(1);
                        orderTeamUser.setTeamId(idGererateFactory.nextStringId());
                        this.orderTeamUserService.insertOrderTeamUser(orderTeamUser);
                    }
                } else {
                    orderTeamUser.setIsMain(1);
                    orderTeamUser.setTeamId(idGererateFactory.nextStringId());
                    this.orderTeamUserService.insertOrderTeamUser(orderTeamUser);
                }
            } else {
                orderTeamUser.setIsMain(1);
                orderTeamUser.setTeamId(idGererateFactory.nextStringId());
                this.orderTeamUserService.insertOrderTeamUser(orderTeamUser);
            }

//            this.orderTeamUserService.insertOrderTeamUser(orderTeamUser);
        }
        return R.error("999");
    }


    /**
     * 支付成功的回调参数
     * @param req
     * @param res
     * @return
     */
    @GetMapping("/result")
    public Object weixinResult(@RequestParam String orderNo){

        OrderTeamOrderDto orderTeamOrder = this.orderTeamOrderService.findByOrderNo(orderNo);
        if (orderTeamOrder!=null){
            if (orderTeamOrder.getStatus()>0){
                return "fail";
            }

            //  验签成功后
            orderTeamOrder.setStatus(9);
            orderTeamOrder.setPayType(OrderPayType.WEIXIN.getValue());
            orderTeamOrder.setUpdateTime(new Date());
//            orderTeamOrder.setOutTradeNo(mapFromXml.get("out_trade_no").toString());
            orderTeamOrderService.updateOrderTeamOrder(orderTeamOrder);

            //产品销量新增

            //查询订单下的规格
            List<OrderTeamGoodsDto> listByOrderId = this.orderTeamGoodsService.findListByOrderId(orderTeamOrder.getId());
            for(OrderTeamGoodsDto orderTeamGoodsDto:listByOrderId){
                GoodsTeam goodsTeam = this.goodsTeamService.selectGoodsTeamById(orderTeamGoodsDto.getGoodsId());
                GoodsTeam update = new GoodsTeam();
                update.setId(goodsTeam.getId());
                update.setMonthlySales(goodsTeam.getMonthlySales()+orderTeamGoodsDto.getTotal());
                this.goodsTeamService.updateGoodsTeam(update);
            }
            //更新支付记录
//            PayLog updatePayLog = new PayLog();
//            updatePayLog.setId(payLog.getId());
//            updatePayLog.setStatus(1);
//            this.payLogService.updatePayLog(updatePayLog);

            // 通过orderId查拼团订单人
            OrderTeamUser orderTeamUserByOrderId = this.orderTeamUserService.findByOrderId(orderTeamOrder.getId());
            // 通过teamID查拼团订单条数
            List<OrderTeamUser> listByTeamId = this.orderTeamUserService.findListByTeamId(orderTeamUserByOrderId.getTeamId());
            // 查订单拼团商品
            OrderTeamGoods orderTeamGoods = this.orderTeamGoodsService.findByOrderId(orderTeamOrder.getId());
            // 查拼团商品
            GoodsTeam goodsTeamById = this.goodsTeamService.selectGoodsTeamById(orderTeamGoods.getGoodsId());
            // 判断是否超过拼团人数
            if (goodsTeamById.getNumber()==listByTeamId.size()) {
                orderTeamOrder.setStatus(1);
                // 拼团人数够了团队人员订单变为待发货
                for (OrderTeamUser OrderTUser:listByTeamId) {
                    OrderTeamOrder teamOrderById = this.orderTeamOrderService.selectOrderTeamOrderById(OrderTUser.getOrderId());
                    if (teamOrderById.getStatus() == 9) {
                        OrderTeamOrder updateTeamOrder = new OrderTeamOrder();
                        updateTeamOrder.setId(teamOrderById.getId());
                        updateTeamOrder.setStatus(1);
                        this.orderTeamOrderService.updateOrderTeamOrder(updateTeamOrder);
                    }

                }
            }

        }
        return R.ok("付款");

    }

    /**
     * 查询用户地址
     * @param uid
     * @return
     */
    @GetMapping("/memeberAddress")
    private R memeberAddress(@RequestParam String uid){
        //查询默认地址信息
        MemberAddress memberAddress = this.memberAddressService.findDefault(uid);
        return RFactory.generateR(memberAddress);
    }

    /**
     * 生成企业号
     * @param len
     * @return
     */
    @GetMapping("/haveID")
    private R haveID(int len){
        //查企业
        List<Company> companyList = companyService.selectCompanyList(new Company());
        for (Company C : companyList) {
            if (C.getCompanyNum() == null) {
                Company company = new Company();
                company.setId(C.getId());
                company.setCompanyNum(idGererateFactory.getUUID(5));
                companyService.updateCompany(company);
            }
        }
        return R.ok();
    }

    /**
     * 发送订阅消息
     * @param openId
     * @return
     */
    @GetMapping("/sendWxMessage")
    private R sendWxMessage(String openId, String orderNo, String money) {
//        SendWxMessage.pushOrderDeliveryNotice(openId, orderNo);//订单发货通知
        SendWxMessage.pushMemberPayment(openId, money);//会员付费成功通知
        return R.ok();
    }

    @Autowired
    private IVipConfigService vipConfigService;
    @Autowired
    private ICompanyApplyService companyApplyService;
    @Autowired
    private IHaoqiCoinRecordService coinRecordService;
    @Autowired
    private IShopConfigService shopConfigService;

    /**
     * 测试成功开通会员
     * @param memberId
     * @return
     */
    @GetMapping("/testOpenVip")
    private R testOpenVip(String outTradeNo, String money) {
        PayLog payLog = this.payLogService.selectPayLogByNo(outTradeNo);
            Date date = new Date();
            String memberId = outTradeNo.split("-")[0];
            Member member = this.memberService.selectMemberByOrderOn(memberId);
            System.out.println("~~~~~~~~~~~~~已查到用户~~~~~~~~~~~~");

            // 验签成功后
            // 会员配置
            VipConfig vipConfig = vipConfigService.selectVipConfigById(payLog.getResId());
            // 会员信息 续费?年
            Member update = new Member();
            update.setId(member.getId());
            if (vipConfig != null) {
                if (vipConfig.getType() == 0) {
                    update.setIsVip(MemberIsVip.YES.getValue());

                    // 如果用户是会员 则 续费?年  否则 改为 当前时间续费?年
                    GregorianCalendar gregorianCalendar1 = new GregorianCalendar();
                    if(member.getIsVip().equals(MemberIsVip.YES.getValue())){
                        if (member.getVipEndTime() != null) {
                            gregorianCalendar1.setTime(member.getVipEndTime());
                        } else {
                            gregorianCalendar1.setTime(DateUtils.getNowDate());
                        }
                    }else{
                        gregorianCalendar1.setTime(DateUtils.getNowDate());
                    }
                    gregorianCalendar1.add(Calendar.YEAR,vipConfig.getVipTime());
                    update.setVipEndTime(gregorianCalendar1.getTime());
                } else {
                    update.setIsJqVip(MemberIsVip.YES.getValue());

                    // 企业会员（先支付后填资料）
                    CompanyApply companyApply = new CompanyApply();
                    companyApply.setMemberId(member.getId());
                    List<CompanyApply> companyApplyList = companyApplyService.selectCompanyApplyList(companyApply);
                    // 有申请改企业申请表的付款状态
                    if (companyApplyList.size() > 0) {
                        companyApply.setId(companyApplyList.get(0).getId());
                        companyApply.setPayStatus(1);
                        companyApply.setIsShow(1);
                        companyApplyService.updateCompanyApply(companyApply);
                    } else {
                        companyApply.setPayStatus(1);
                        companyApply.setIsShow(0);
                        companyApplyService.insertCompanyApply(companyApply);
                    }


                    // 如果企业是会员 则 续费?年  否则 改为 当前时间续费?年
                    GregorianCalendar gregorianCalendar2 = new GregorianCalendar();
                    if(member.getIsJqVip().equals(MemberIsVip.YES.getValue())){
                        if (member.getJqVipEndTime() != null) {
                            gregorianCalendar2.setTime(member.getJqVipEndTime());
                        } else {
                            gregorianCalendar2.setTime(DateUtils.getNowDate());
                        }
                    }else{
                        gregorianCalendar2.setTime(DateUtils.getNowDate());
                    }
                    gregorianCalendar2.add(Calendar.YEAR,vipConfig.getVipTime());
                    update.setJqVipEndTime(gregorianCalendar2.getTime());
                }
            }
            this.memberService.updateMember(update);
            System.out.println("~~~~~~~~~~~~~已变成会员~~~~~~~~~~~~");

            // 给推荐人返佣
            Member introUser = memberService.selectMemberById(member.getIntroUser());// 推荐人信息
            if (introUser != null) {
                List<ShopConfig> shopConfigAll = shopConfigService.findAll();
                HaoqiCoinRecord coinRecord = new HaoqiCoinRecord();
                coinRecord.setMemberId(member.getIntroUser());
                if (payLog.getVip() == 0) {
                    coinRecord.setNum(shopConfigAll.get(0).getVipPrice());
                    coinRecord.setGetType(1);
                } else {
                    coinRecord.setNum(shopConfigAll.get(0).getVipReturnRatio());
                    coinRecord.setGetType(2);
                }
                coinRecord.setStatus(1);
                coinRecord.setType(0);
                coinRecord.setResId(member.getId());
                coinRecordService.insertHaoqiCoinRecord(coinRecord);
                System.out.println("~~~~~~~~~~~~~已给推荐人返佣~~~~~~~~~~~~");
            }

            //更新支付记录
            PayLog updatePayLog = new PayLog();
            updatePayLog.setId(payLog.getId());
            updatePayLog.setStatus(1);
            this.payLogService.updatePayLog(updatePayLog);
            System.out.println("~~~~~~~~~~~~~已更新支付记录~~~~~~~~~~~~");

        return R.ok();
    }

    @Autowired
    private IQuotationService quotationService;

    /**
     * 测试定时删除行情
     * @param openId
     * @return
     */
    @GetMapping("/deleteQuotation")
    private R deleteQuotation(String id) {
        //假删除行情
//        Quotation quotation = new Quotation();
//        quotation.setDelFlag(0);
//        List<Quotation> quotationList = quotationService.selectQuotationList(quotation);
//        for (Quotation Q : quotationList) {
        Quotation quotationById = quotationService.selectQuotationById(id);
        Date nowDate = new Date();//当前时间
            Calendar cal = Calendar.getInstance();
            cal.setTime(nowDate);
            cal.add(Calendar.DATE, -30);//30天
            //删除30天前记录
        if (cal.getTime().compareTo(quotationById.getReleaseDate()) > 0) {
            System.out.println(cal.getTime());
            }
//        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("30天前=",cal.getTime());
        map.put("行情时间=",quotationById.getReleaseDate());
        return R.ok(map);
    }
}
